package com.example.musicdemo.views;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.musicdemo.R;
import com.example.musicdemo.adapter.MediaCursorAdapter;
import com.example.musicdemo.listener.OnMusicPlayStateChangeListener;
import com.example.musicdemo.service.MusicService;
import com.example.musicdemo.utils.Utils;


public class MainActivity extends AppCompatActivity implements View.OnClickListener,
        SeekBar.OnSeekBarChangeListener, AdapterView.OnItemClickListener, OnMusicPlayStateChangeListener {

    public static final int UPDATE_PROGRESS = 1;
    private static final int REQUEST_READ_MEDIA_AUDIO = 1;
    private static final int REQUEST_READ_MEDIA_IMAGES = 2;

    private ListView mPlaylist;//播放列表
    private TextView tvBottomTitle;//音乐名
    private TextView tvBottomArtist;//歌手名
    private ImageView ivAlbumThumbnail;
    private ImageView ivPlay;
    private ImageView ivLast;
    private ImageView ivNext;
    private SeekBar pbProgress;//播放进度条
    private TextView mTimeView;//展示播放时间
    private MusicService mService;
    private MyServiceConnection mConnection;
    private Cursor mCursor;
    private MediaCursorAdapter mCursorAdapter;
    private int mDuration;//总进度(总时间)
    private boolean mPlayStatus = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        mPlaylist = findViewById(R.id.music_list);
        mCursorAdapter = new MediaCursorAdapter(this);
        mPlaylist.setAdapter(mCursorAdapter);
        mPlaylist.setOnItemClickListener(this);
        ivPlay = findViewById(R.id.iv_play);
        ivNext = findViewById(R.id.iv_next);
        ivLast = findViewById(R.id.iv_last);
        ivPlay.setOnClickListener(this);
        ivNext.setOnClickListener(this);
        ivLast.setOnClickListener(this);
        tvBottomTitle = findViewById(R.id.tv_bottom_title);
        tvBottomArtist = findViewById(R.id.tv_bottom_artist);
        ivAlbumThumbnail = findViewById(R.id.iv_thumbnail);
        ivAlbumThumbnail.setOnClickListener(this);
        pbProgress = findViewById(R.id.progress);
        pbProgress.setOnSeekBarChangeListener(this);
        mTimeView = findViewById(R.id.time);
        mConnection = new MyServiceConnection();
        requestPermission();
    }

    private void bindService() {
        Intent intent = new Intent(MainActivity.this, MusicService.class);
        startForegroundService(intent);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onPlayStart() {
        if (mService != null) {
            mDuration = mService.getDuration();
            Log.d("asdf", "总时长:" + mDuration);
            pbProgress.setMax(mDuration);
            ivPlay.setImageResource(R.mipmap.pause);
            new Thread(new MusicProgressRunnable()).start();
        }
    }

    @Override
    public void onPlayStop() {

    }

    @Override
    public void onPlayComplete() {

    }

    @Override
    public void onMusicInfoChanged(String title, String artist) {
        if (tvBottomTitle != null) {
            tvBottomTitle.setText(title);
        }
        if (tvBottomArtist != null) {
            tvBottomArtist.setText(artist);
        }
    }

    @Override
    public void onMusicListChanged(Cursor cursor) {
        if (mCursor == null) {
            mCursor = cursor;
            Log.d("asdf", "=====onMusicListChanged");
            notifyDataChanged();
        }
    }

    private void notifyDataChanged() {
        if (mCursorAdapter != null) {
            mCursorAdapter.changeCursor(mCursor);
            mCursorAdapter.notifyDataSetChanged();
        }
    }

    private class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d("asdf", "=====onServiceConnected=====");
            mService = ((MusicService.MyBinder) service).getService();
            mService.setOnMusicPlayStateChangeListener(MainActivity.this);
            mCursor = mService.getCursor();
            notifyDataChanged();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }
    }


    @Override
    public void onClick(View v) {
        if (mService == null) {
            return;
        }
        int id = v.getId();
        if (id == R.id.iv_play) {
            mPlayStatus = !mPlayStatus;
            if (mPlayStatus) {
                mService.play();
                ivPlay.setImageResource(R.mipmap.pause);
            } else {
                mService.pause();
                ivPlay.setImageResource(R.mipmap.play);
            }
        } else if (id == R.id.iv_last) {
            mService.last();
        } else if (id == R.id.iv_next) {
            mService.next();
        } else if (id == R.id.iv_thumbnail) {
            Intent intent = new Intent(MainActivity.this, MusicActivity.class);
            startActivity(intent);
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (mService != null && fromUser) {
            mService.seekTo(progress);//拖动进度条，改变播放进度
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(mService != null) {
            mService.getDataByCursor(position);
        }
    }

    private void requestPermission() {
        // 获取读取sd卡的权限
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_MEDIA_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_MEDIA_AUDIO}, REQUEST_READ_MEDIA_AUDIO);
        } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_MEDIA_IMAGES}, REQUEST_READ_MEDIA_IMAGES);
        } else {
            bindService();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_READ_MEDIA_AUDIO) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                bindService();
            }
        }
        if (requestCode == REQUEST_READ_MEDIA_IMAGES) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                bindService();
            }
        }
    }

    private class MusicProgressRunnable implements Runnable {
        public MusicProgressRunnable() {
        }

        @Override
        public void run() {
            boolean mThreadWorking = true;
            while (mThreadWorking) {
                try {
                    if (mService != null) {
                        int position = mService.getCurrentPosition();
                        //Log.d("asdf", String.valueOf(position));
                        Message message = new Message();
                        message.what = UPDATE_PROGRESS;
                        message.arg1 = position;
                        mHandler.sendMessage(message);
                    }
                    mThreadWorking = mService.isPlaying();
                    Thread.sleep(100);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_PROGRESS:
                    int position = msg.arg1;
                    pbProgress.setProgress(position);//设置当前进度(当前时间)
                    mTimeView.setText(Utils.formatMsToMMSS(position) + "/" + Utils.formatMsToMMSS(mDuration));// 当前时间/总时间
                    break;
                default:
                    break;
            }
        }
    };
}